// pages/play/play.js
const common = require("../../common/js/common.js");
const controlIcon = {
  stop: "../../assets/stop.png",
  play: "../../assets/play.png"
};
Page({
  data: {
    picSrc: "",
    playBorder:
      "http://s3.music.126.net/m/s/img/disc-ip6.png?69796123ad7cfe95781ea38aac8f2d48",
    lyricObj: {},
    progressValue: 0,
    playLoop: false,
    initIcon: controlIcon.stop,
    slideMaxValue: -1,
    flagDrag: false,
    scrollView: "",
    formatShowTime: [],
    songName_singer: '',
    stopFlag: false,
    musicSrc: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let id = options.id;
    let that = this;
    common.http({
      url: common.baseUrl + "/lyric",
      query: {
        id: id
      },
      success(data) {
        console.log(data);
        let lyricObj = formatLyric(data.lrc.lyric);
        that.setData({
          formatShowTime: formatShowTimeFun(lyricObj.lyricTime),
          lyricObj: lyricObj
        });
      },
      fail(err) {
        common.coustomToast({
          title: err
        });
      }
    });
    common.http({
      url: common.baseUrl + "/song/detail",
      query: {
        ids: id
      },
      success(data) {
        console.log(data);
        that.setData({
          picSrc: data.songs[0].al.picUrl,
          songName_singer: data.songs[0].name
        });
      }, fail(err) {
        common.coustomToast({
          title: err
        });
      }
    });
    common.http({
      url: common.baseUrl + "/music/url",
      query: {
        id: id
      },
      success(data) {
        that.setData({
          musicSrc: data.data[0].url
        });
      }, fail(err) {
        common.coustomToast({
          title: err
        });
      }
    });
    this.playAudio = wx.getBackgroundAudioManager();
    this.audioOnPlay();
    this.audioOnStop();
    this.audioOnPause();
    this.audiOnError();
    this.audioOnEnded();
    this.getNowAudioStatus();
    this.audioUpdateTime();
  },
  onReady: function () { },
  onShow: function () { },
  onHide: function () { },
  onUnload: function () { },
  dragSongFun(e) {
    this.playAudio.seek(e.detail.value);
    e.detail.value == this.playAudio.duration ? null : this.audioPlay();
    this.setData({
      flagDrag: false,
      progressValue: e.detail.value
    });
  },
  dragSongFuning(e) {
    this.setData({
      flagDrag: true
    });
  },
  audioPlay() {
    console.log("播放play");
    let that = this;
    if (that.data.stopFlag) {
      if (common.customTrim(that.data.musicSrc) == "") {
        console.log("播放错误");
        return;
      }
      common.bgMusic.bgPlay(that.data.musicSrc, '', '', (data) => {
        console.log(JSON.stringify(data) + "播放");
        that.setData({
          stopFlag: false
        });
      }, (err) => {
        console.log(JSON.stringify(err) + "错误");
      });
    } else {
      that.playAudio.play();
    }
  },
  audioPause() {
    this.playAudio.pause();
  },
  audioOnEnded() {
    let that = this;
    that.playAudio.onEnded(() => {
      that.setData({
        initIcon: controlIcon.stop,
        stopFlag: true
      });
    });
  },
  audioOnPlay() {
    let that = this;
    that.playAudio.onPlay(() => {
      console.log("—————播放监听————");
      that.setData({
        initIcon: controlIcon.play
      });
    });
  },
  audioOnStop() {
    let that = this;
    that.playAudio.onStop(() => {
      console.log("—————停止监听————");
      that.setData({
        initIcon: controlIcon.stop,
        stopFlag: true
      });
    });
  },
  audioOnPause() {
    let that = this;
    that.playAudio.onPause(() => {
      console.log("—————pause监听————");
      that.setData({
        initIcon: controlIcon.stop
      });
    });
  },
  audiOnError() {
    let that=this;
    that.playAudio.onError(res => {
      that.setData({
        initIcon: controlIcon.stop,
        stopFlag: true
      });
    });
  },
  audioOnWaiting() {
    this.playAudio.onWaiting(res => {
      console.log("等待中...");
    });
  },
  getNowAudioStatus() {
    this.setData({
      slideMaxValue: this.playAudio.duration
    });
    this.setData({
      progressValue: this.playAudio.currentTime
    });
    if (this.playAudio.paused) {
      this.setData({
        initIcon: controlIcon.stop
      });
    } else {
      this.setData({
        initIcon: controlIcon.play
      });
    }
  },
  audioUpdateTime() {
    let that = this;
    this.playAudio.onTimeUpdate(() => {
      if (!that.data.flagDrag) {
        let scrollViewTo = (
          "lyric" +
          calLyricLocation(
            that.playAudio.currentTime,
            that.data.lyricObj.lyricTime
          )
        ).replace(".", "");
        if (that.data.scrollView != scrollViewTo) {
          that.setData({
            scrollView: scrollViewTo
          });
        }
        that.setData({
          progressValue: that.playAudio.currentTime
        });
      }
    });
  },
  stopSongFun() {
    if (this.playAudio.paused) {
      this.audioPlay();
    } else {
      this.audioPause();
    }
  },
  preSongFun() {
    common.coustomToast({
      title: '未完成'
    });
  },
  nextSongFun() {
    common.coustomToast({
      title: '未完成'
    });
  },
  lyricScrollFun(e) { }
});

function formatLyric(data) {
  let lyricObj = {};
  let lyricTime = [];
  let lyricTxt = [];
  let lyricLine = data.split(/\n/g);
  lyricLine.pop();
  lyricLine.forEach(n => {
    let lyricArray = n.split("]");
    if (!(common.customTrim(lyricArray[1]) == "" || common.customTrim(lyricArray[1]) == undefined)) {
      let time = lyricArray[0].replace("[", "").split(":");
      if (time.length != 1) {
        if (!isNaN(time[0] * 60 - 0 + (time[1] - 0))) {
          lyricTime.push(time[0] * 60 - 0 + (time[1] - 0));
        }
      }
      lyricTxt.push(lyricArray[1]);
    }
  });
  lyricObj.lyricTxt = lyricTxt;
  lyricObj.lyricTime = lyricTime;
  console.log(lyricObj);
  return lyricObj;
}

function calLyricLocation(currentTime, lyricTimeArray) {
  let scrollId = "";
  for (let i = 0; i < lyricTimeArray.length; i++) {
    if (currentTime < lyricTimeArray[i]) {
      scrollId = lyricTimeArray[i - 1];
      break;
    }
  }
  return scrollId;
}

function formatShowTimeFun(oldTime) {
  let newTime = [];
  oldTime.forEach(n => {
    newTime.push(("lyric" + n).replace(".", ""));
  });
  return newTime;
}
function errorType(type) {
  let str;
  switch (type) {
    case 10001:
      str = "系统错误";
      break;
    case 10002:
      str = "网络错误";
      break;
    case 10003:
      str = "文件错误";
      break;
    case 10004:
      str = "格式错误";
      break;
    case -1:
      str = "未知错误";
      break;
    default:
      str = "unknown"
      break;
  }
  return str;
}